import util from '../../utils/index'
import {
  itemModel
} from '../../apis/index.js'
const app =  getApp();

Page({
  data: {
    maxCount:8,
    currentCount:0,
    list:[],
    new_head_path:''  
  },

  onLoad: function (options) {
    // this.data.userInfo = util.getStorageSync('user_info') || {}
    // if(!this.data.userInfo){
    //   util.showToast('用户信息获取失败')
    //   setTimeout(()=>{
    //     util.navigateBack()
    //   },1500)
    // }
    // this.setData({
    //   userInfo:this.data.userInfo
    // })
    this.getLeaseList()
  },
  chooseImage(){
    
    util.chooseImage({
      count:1,
      sizeType: ['original','compressed'],
      sourceType: ['album','camera'],
      success: (res)=>{
        let path = res.tempFilePaths[0]
        let param = {
          filePath:path
        }
        util.showLoading('上传中...')
        itemModel.uploadHeadImage(param).then(res=>{
          let {url} = res
          this.data.new_head_path  =`${util.imageUrl}${url}`
          this.setData({
            avatar:this.data.new_head_path
          },()=>{
            util.hideAll()
          }) 
        }).catch(()=>{
          util.showToast('上传失败','none')
          setTimeout(()=>{
            util.hideAll()
          },1500)
        })
      }
    })
  },
  selectItem(e){
    let index = e.currentTarget.dataset.index
      let list = this.data.list
      let item = list[index]
      let checked = item.checked?false:true
      if((this.data.currentCount<this.data.maxCount)||((this.data.currentCount>=this.data.maxCount)&&!checked )){
        item.checked = checked
        this.setData({
          list:list
        })
        item.checked?this.data.currentCount++:this.data.currentCount--
      }else{
        util.showToast('最多只能选择8个','none')
      }
  },
  getLeaseList(){
    util.showLoading()
    itemModel.leaseList().then(res=>{
      let {avatar,list} = res
      list.forEach(el => {
        el.checked = false
      })
      this.setData({
        avatar:avatar,
        list:list
      },()=>{
        util.hideAll()
      })
    }).catch(()=>{
      util.hideAll()
    })
  },
  makeRent(){
    let {list} = this.data
    let arr = []
    let _arr = []
    list.forEach(el => {
      if(el.checked){
        let temp = {
          [el.id]:el.price
        }
        let _temp = {
          id:el.id,
          price:el.price,
          name:el.title
        }
        arr.push(temp)
        _arr.push(_temp)
      }
    })
    if(arr.length==0){
      util.showToast('请选择出租项目','none')
      return false
    }
    let param = {
      content:JSON.stringify(arr),
      avatar:this.data.new_head_path
    }
    itemModel.makeLease(param).then(res=>{
      app.globalData.rent_data ={
        rent_id:res.lid,
        list:_arr
      } 
      util.goUrl('../makeRent/makeRent')
    })
  }
})